import Data from '@/utils/data'
import Api from '@/api'
const token = Data.getToken()
const user = Data.getUser()
const data = Data
const login = Api.Login
const Personal = Api.Personal
import { resetRouter } from '@/router'
const state = {
	token: token,
	user: user,
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_USER: (state, user) => {
		state.user = user
	},
	removeToken: state => {
		state.token = ''
		data.clearToken()
	},
	removeUser: state => {
		state.user = ''
		data.clearUser()
	},
}

const actions = {
	// // user login
	login({ commit }, params) {
		return new Promise((resolve, reject) => {
			login
				.submit(params)
				.then(response => {
					console.log('response', response)
					commit('SET_TOKEN', response.token)
					commit('SET_USER', response.user)
					Data.setToken(response.token)
					Data.setUser(response.user)
					resolve()
				})
				.catch(error => {
					reject(error)
				})
		})
	},
	// // user logout
	logout({ commit, state }) {
		commit('removeToken')
		commit('removeUser')
		resetRouter()
	},
	// 获取用户详情
	getUserInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			Personal.getUserInfo()
				.then(response => {
					commit('SET_USER', response)
					Data.setUser(response)
					resolve(response)
				})
				.catch(error => {
					reject(error)
				})
		})
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
}
